<?php
namespace Budget\BudgetBundle\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class FamilyController extends MainController
{
    public function calculateMonthAction(Request $request)
    {
        $response     = new \stdClass();
        $em           = $this->getEntityManager();
        $familyMonth  = $em->getRepository('BudgetBudgetBundle:FamilyMonth')
                            ->findByIdForFamily($this->getUser()->getFamily(), $request->request->get('monthId'));
        
        $now = new \Datetime();
        if (is_null($familyMonth)) {
            $response->status = false;
            $response->msg    = 'Wybrany miesiąc nie istnieje!';
        } else if($familyMonth->getEnd() > $now) {
            $response->status = false;
            $response->msg    = 'Miesiąc nie został zakończony!';
        } else {
            $amountLeft = $this->get('statistic')->calculateAmountLeft($familyMonth);
            
            $response->status     = true;
            $response->amountLeft = $amountLeft;
            $response->msg        = 'Rozliczenie zakończone. Pozostało: ' . number_format($amountLeft, 2) . ' zł';
            //save to db;
            $familyMonth->setAmountLeft(number_format($amountLeft, 2, '.', ''));
            $em->persist($familyMonth);
            $em->flush();
        }
        
        return new JsonResponse($response);
    }
  
}